package com.itheima.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.constant.TokenConstant;
import com.itheima.pojo.Employee;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MetaObjectHandlerConfig implements MetaObjectHandler {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    private Long getAuditId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        String auditEmpStr = (String) redisTemplate.opsForValue().get(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token);
        Employee auditEmp = JSON.parseObject(auditEmpStr, Employee.class);
        if (auditEmp == null) {
            request.getRequestDispatcher("/employee");
        }
        Long auditId = auditEmp.getId();
        return auditId;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        Long auditId = this.getAuditId();
        this.strictInsertFill(metaObject, "createUser", Long.class, auditId);
        this.strictInsertFill(metaObject, "updateUser", Long.class, auditId);
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long auditId = this.getAuditId();
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateUser", Long.class, auditId);
    }
}